import 'dart:convert';
import 'dart:ui';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:yd_eval/entity/yd_api_eval_result_entity.dart';
import 'package:yd_eval/manager/yd_eval_manager.dart';

typedef OnLongOrClickListener = void Function(String word);

class EvalResultUtils {
  static EvalResultUtils instance = _instance ??= EvalResultUtils._internal();

  static EvalResultUtils? _instance;

  EvalResultUtils._internal();

  var STAR_ONE = 40.0;
  var STAR_TWO = 50.0;
  var STAR_THREE = 60.0;
  var STAR_FOUR = 75.0;
  var STAR_FIVE = 85.0;

  //英语评测保留
  List<String> SYMBOL = [
    'A',
    'a',
    'B',
    'b',
    'C',
    'c',
    'D',
    'd',
    'E',
    'e',
    'F',
    'f',
    'G',
    'g',
    'H',
    'h',
    'I',
    'i',
    'J',
    'j',
    'K',
    'k',
    'L',
    'l',
    'M',
    'm',
    'N',
    'n',
    'O',
    'o',
    'P',
    'p',
    'Q',
    'q',
    'R',
    'r',
    'S',
    's',
    'T',
    't',
    'U',
    'u',
    'V',
    'v',
    'W',
    'w',
    'X',
    'x',
    'Y',
    'y',
    'Z',
    'z',
    '\'',
    ' ',
    'ˈ',
    'ː',
    'ˌ',
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'æ',
    'ɪ',
    'ɜ',
    'ɑ',
    'ə',
    'ɔ',
    'ʊ',
    'ʃ',
    'ʒ',
    'ð',
    'ŋ',
    'ʌ',
    'θ',
    'ɒ',
    '/'
  ];

  TextStyle _defaultTextStyle = const TextStyle();

  OnLongOrClickListener? _onClickListener;
  OnLongOrClickListener? _onLongListener;

  /// 获取总分
  double getScore(YdApiEvalResultEntity? entity) {
    if (entity == null) {
      return 0;
    }
    return entity.result?.pronunciation ?? 0;
  }

  /// 获取流畅度评分
  double getFluencyScore(YdApiEvalResultEntity? entity) {
    if (entity == null) {
      return 0;
    }
    return entity.result?.fluency ?? 0;
  }

  /// 获取完整度评分
  double getIntegrityScore(YdApiEvalResultEntity? entity) {
    if (entity == null) {
      return 0;
    }
    return entity.result?.integrity ?? 0;
  }

  /// 获取准确度评分
  double getAccuracyScore(YdApiEvalResultEntity? entity) {
    if (entity == null) {
      return 0;
    }
    return entity.result?.pronunciation ?? 0;
  }

  /// 获取评分标准
  List<double> get getEvalScoreStandard =>
      [STAR_ONE, STAR_TWO, STAR_THREE, STAR_FOUR, STAR_FIVE];

  void setupIndex(String? text, String? type, Map<int, int> indexMap) {
    indexMap.clear();
    if (text == null) {
      return;
    }

    print("评测的文本: $text");

    // [PS]空格是音标标记，不参与打分
    String textA = text.replaceAll("[PS] ", "");

    print("[PS]空格是音标标记，不参与打分，匹配index的时候去掉[PS]空格: $textA");

    StringBuffer textB = StringBuffer();

    if (type == YdEvalType.TYPE_ZH) {
      // 汉字正则
      RegExp regex = RegExp(r'[\u4e00-\u9fa5]');

      for (int i = 0; i < textA.length; i++) {
        String c = textA[i];
        if (regex.hasMatch(c)) {
          textB.write(c);
        } else {
          textB.write(' ');
        }
      }

      print("过滤字符串，属于汉字的保留，不属于的其他符号都替换成空格: ${textB.toString()}");

      // 多个空格相邻合并成一个空格
      String textC = textB.toString().replaceAll(RegExp(r' +'), '');
      print("去掉空格: $textC");

      int preI = 0;
      for (int index = 0; index < textC.length; index++) {
        String s = textC[index];
        int i = text.indexOf(s, preI);
        if (i >= 0) {
          indexMap[index] = i;
          preI = i + 1;
        }
      }
    } else {
      // 过滤字符串，属于symbol里面的保留
      for (int i = 0; i < textA.length; i++) {
        String c = textA[i];
        if (SYMBOL.contains(c)) {
          // SYMBOL 应该是一个包含符号的集合
          textB.write(c);
        } else {
          textB.write(' ');
        }
      }

      print("过滤字符串，属于symbol里面的保留，不属于的其他符号都替换成空格: ${textB.toString()}");

      // 多个空格相邻合并成一个空格
      String textC = textB.toString().replaceAll(RegExp(r' +'), ' ').trim();

      print("多个空格相邻合并成一个空格: $textC");

      List<String> split = textC.split(' ');

      print("然后按空格切分string，切分出来的列表index从0开始");

      int preI = 0;
      for (int index = 0; index < split.length; index++) {
        String s = split[index];
        int i = text.indexOf(s, preI);
        if (i >= 0) {
          indexMap[index] = i;
          preI = i + s.length;
        }
      }
    }

    print("结果: $indexMap");
  }

  List<dynamic> parseResult(
      YdApiEvalResultEntity? entity, String? originText, String type) {
    double overall = 0.0;
    List<InlineSpan> textSpans = [];

    if (entity != null && entity.result != null && originText != null) {
      try {
        var result = entity.result!;
        overall = result.overall ?? 0.0;

        String? refText = result.refText;

        if (refText != null) {
          Map<int, int> indexMap = {};
          setupIndex(refText, type, indexMap);

          // textSpans.add(TextSpan(text: refText)); // 添加原始文本

          int prePosition = 0;

          int lastIndex = 0;
          if (result.words != null) {
            for (int i = 0; i < result.words!.length; i++) {
              var wordObj = result.words![i];
              double score = wordObj.pronunciation ?? 0;
              String word = wordObj.word ?? "";
              int position = wordObj.index ?? 0;

              if (word.isEmpty) continue;

              int? index = indexMap[position];

              /// 单词在原文中的位置
              int originWordIndex = originText.indexOf(word, lastIndex);

              if (index != null && originWordIndex > index) {
                // 加入符号
                textSpans.add(setSan(originText, lastIndex, originWordIndex,
                    const Color(0xff40423E)));
                lastIndex = originWordIndex + word.length;
              }

              // 如果 indexMap 中有该单词，index 开始查找
              index ??= refText.indexOf(word, position);

              // 如果上面都没找到，那就从 prePosition 位置查找
              if (index < 0) {
                index = refText.indexOf(word, prePosition);
                if (index >= 0) {
                  prePosition = index;
                }
              }

              // 如果最后上面都没找到，那就从 0 位置查找吧
              if (index < 0) {
                index = refText.indexOf(word);
              }

              if (index >= 0) {
                Color color;
                if (score >= STAR_FOUR) {
                  color = const Color(0xFF74D95F); // 示例颜色
                } else if (score >= STAR_ONE) {
                  color = const Color(0xFFFFB604); // 示例颜色
                } else {
                  color = const Color(0xFFFF7040); // 示例颜色
                }

                // 使用 setSan 函数创建带有颜色的 TextSpan
                textSpans
                    .add(setSan(refText, index, index + word.length, color));

                // 判断是否为最后一次循环
                if (i == result.words!.length - 1) {
                  debugPrint("进入最后一次循环了！ $lastIndex , $word "
                      ",总长度 ${originText.length} ，"
                      "长度：${lastIndex + word.length},"
                      "截取后：${originText.substring(lastIndex)}");
                  if (lastIndex < originText.length) {
                    textSpans.add(setSan(
                        originText, lastIndex, null, const Color(0xff40423E)));
                  }
                }
              }
            }
          }
        }
      } catch (e) {
        print("parseResult 结果解析错误： ==> ${e.toString()}");
      }
    }

    return [overall, textSpans]; // 返回包含所有 TextSpan 的列表
  }

  TextSpan setSan(String text, int start, int? end, Color? color) {
    debugPrint(
        "截取单词：${text.substring(start, end)},start => $start,end => $end,");

    String word = text.substring(start, end);

    final TapGestureRecognizer tapGestureRecognizer = TapGestureRecognizer()
      ..onTap = () {
        _onClickListener?.call(word);
      };

    final LongPressGestureRecognizer longPressGestureRecognizer =
        LongPressGestureRecognizer()
          ..onLongPress = () {
            _onLongListener?.call(word);
          };

    // 创建一个 TextSpan，设置指定范围的文本颜色
    return TextSpan(
      text: word,
      style: color == null
          ? _defaultTextStyle.copyWith(color: color)
          : _defaultTextStyle,
      recognizer: _onClickListener != null
          ? tapGestureRecognizer
          : longPressGestureRecognizer,
    );
  }

  void setDefaultTextStyle(TextStyle style) {
    _defaultTextStyle = style;
  }

  void setTextTop(OnLongOrClickListener listener) {
    _onClickListener = listener;
  }

  void setTextLongTop(OnLongOrClickListener listener) {
    _onLongListener = listener;
  }

  /// 根据分数获取对应的音频文件
  String getAudioName(double score) {
    var s = score;
    if (s >= STAR_FIVE) {
      return "eval_excellent_audio.mp3";
    }
    if (s >= STAR_FOUR) {
      return "eval_good_audio.mp3";
    }
    if (s >= STAR_THREE) {
      return "eval_good_audio.mp3";
    }
    if (s >= STAR_TWO) {
      return "eval_medium_audio.mp3";
    }
    if (s >= STAR_ONE) {
      return "eval_medium_audio.mp3";
    }
    return "eval_bad_audio.mp3";
  }


  /// 获取评测得分星级
  int getStarCount(double totalScore) {
    var scoreList = getEvalScoreStandard;
    // var totalScore = getScore();
    var scoreStar = 0;
    if (totalScore >= scoreList[4]) {
      scoreStar = 5;
    } else if (totalScore >= scoreList[3]) {
      scoreStar = 4;
    } else if (totalScore >= scoreList[2]) {
      scoreStar = 3;
    } else if (totalScore >= scoreList[1]) {
      scoreStar = 2;
    } else if (totalScore >= scoreList[0]) {
      scoreStar = 1;
    } else {
      scoreStar = 0;
    }
    return scoreStar;
  }



}


extension StringExtension on String {
  /// 判断是否为中文
  bool isChinese() {
    return RegExp(r'[\u4e00-\u9fa5]').hasMatch(this);
  }

  /// 判断是否为英文
  bool isEnglish() {
    return RegExp(r'[a-zA-Z]').hasMatch(this);
  }

  /// 判断单个字符是否为中文
  bool isChineseCharacter() {
    int codeUnit = codeUnitAt(0);
    return (codeUnit >= 0x4e00 && codeUnit <= 0x9fa5);
  }

  /// 判断字符是否为字母
  bool isLetter() {
    int codeUnit = codeUnitAt(0);
    return ((codeUnit >= 0x0041 && codeUnit <= 0x005A) ||
        (codeUnit >= 0x0061 && codeUnit <= 0x007A));
  }
}
